package com.bhzyxy.love;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bhzyxy.love.http.CommonCallback;
import com.bhzyxy.love.http.CommonHttp;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Objects;

public class LoveActivity extends AppCompatActivity {

    public static JSONObject jsonObject;
    private AppCompatEditText keywordEditText = null;
    private AppCompatTextView searchTextView = null;
    private RecyclerView mainRecyclerView = null;
    private AppCompatTextView clearTextView = null;
    private AppCompatImageButton member = null;
    private AppCompatImageButton show = null;
    private ArrayList<LoveData> arrayList = new ArrayList<>();
    private LoveAdapter mainAdapter = new LoveAdapter(arrayList);

    public static boolean isLogin = false;
    public static CommonHttp commonHttp = null;
    public static SharedPreferences sharedPreferences = null;
    public static SharedPreferences.Editor editor = null;

    @SuppressLint({"SetJavaScriptEnabled", "CommitPrefEdits"})

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_love);
        keywordEditText = findViewById(R.id.keywordEditText);
        searchTextView = findViewById(R.id.searchTextView);
        mainRecyclerView = findViewById(R.id.mainRecyclerView);
        clearTextView = findViewById(R.id.clearTextView);
        member = findViewById(R.id.member);
        show = findViewById(R.id.show);

        sharedPreferences = getSharedPreferences("Test", MODE_PRIVATE);
        editor = sharedPreferences.edit();

        //初始化我们自行封装的okgo
        commonHttp = new CommonHttp(getApplication(), Common.API_URL, sharedPreferences.getString("token", ""));

        //初始化OKGO,给它添加一个公共的参数token
        // ctrl + shift + r
        HttpParams httpParams = new HttpParams();
        httpParams.put("token", sharedPreferences.getString("token", ""));
        OkGo.getInstance().addCommonParams(httpParams).init(getApplication());

        //是否登录
        String token = sharedPreferences.getString("token", "");
        isLogin = !token.isEmpty();
        if (isLogin) {
            commonHttp.post("member/getData/", null, new CommonCallback() {
                @Override
                public void onSuccess(String data) {

                }

                @Override
                public void onFailure(String msg) {
                    //请求失败,代表token已失效...

                }
            });
        }

        //设置一个布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mainRecyclerView.setLayoutManager(linearLayoutManager);
        //设置对应的适配器
        mainRecyclerView.setAdapter(mainAdapter);

        mainAdapter.setOnItemClickListener(new LoveAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, LoveData bean) {
                Intent intent = new Intent();
                intent.putExtra("file", bean.getAvatar());
                finish();
            }


            @Override
            public void onDelete(int position, LoveData bean) {
                //构建提交的数据
                HttpParams httpParams = new HttpParams();
                httpParams.put("id", bean.getId());
                OkGo.<String>post(Common.API_URL + "member/deletelove/").tag(this).params(httpParams).execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String data = response.body();
                        try {
                            JSONObject jsonObject = new JSONObject(data);
                            String code = jsonObject.getString("code");
                            if (!code.equals("1")) {
                                String msg = jsonObject.getString("msg");
                                Toast.makeText(LoveActivity.this, msg, Toast.LENGTH_SHORT).show();
                                return;
                            }
                            Toast.makeText(LoveActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });

        searchTextView.setOnClickListener(view -> {
            //从编辑框拿到输入的关键字
            String keyword = Objects.requireNonNull(keywordEditText.getText()).toString();
            //构建提交的数据
            HttpParams httpParams1 = new HttpParams();
            httpParams1.put("keyword", keyword);
            LoveActivity.commonHttp.post("member/getLove/", httpParams1, new CommonCallback() {
                @Override
                public void onSuccess(String data) {
                    try {
                        arrayList.clear();
                        LoveData loveData = null;
                        JSONArray jsonArray = new JSONArray("data");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            loveData = new LoveData();
                            loveData.setId(jsonObject.getString("love_id"));
                            loveData.setText(jsonObject.getString("text"));
                            loveData.setAvatar(jsonObject.getString("love_avatar"));
                            loveData.setAvatarUrl(jsonObject.getString("avatar_url"));
                            arrayList.add(loveData);
                        }
                        mainAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(String msg) {

                }
            });
        });

        HttpParams httpParams1 = new HttpParams();
        OkGo.<String>post(Common.API_URL + "member/getLove/").tag(this).params(httpParams1).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String data = response.body();
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String code = jsonObject.getString("code");
                    if (!code.equals("1")) {
                        String msg = jsonObject.getString("msg");
                        Toast.makeText(LoveActivity.this, msg, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //处理数据
                    arrayList.clear();
                    LoveData loveData = null;
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        jsonObject = jsonArray.getJSONObject(i);
                        loveData = new LoveData();
                        loveData.setId(jsonObject.getString("love_id"));
                        loveData.setText(jsonObject.getString("text"));
                        loveData.setAvatar(jsonObject.getString("love_avatar"));
                        loveData.setAvatarUrl(jsonObject.getString("avatar_url"));
                        arrayList.add(loveData);
                    }
                    mainAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        clearTextView.setOnClickListener(view -> {
            //请求接口，实现清除书签功能
            OkGo.<String>post(Common.API_URL + "member/clearlove/").tag(this).execute(new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    String data = response.body();
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        String code = jsonObject.getString("code");
                        if (!code.equals("1")) {
                            String msg = jsonObject.getString("msg");
                            Toast.makeText(LoveActivity.this, msg, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        //处理数据
                        Toast.makeText(LoveActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        });

        member.setOnClickListener(v -> {
            if (isLogin) {
                Toast.makeText(LoveActivity.this, "您已登录", Toast.LENGTH_SHORT).show();
                return;
            }
            startActivity(new Intent(LoveActivity.this,LoginActivity.class));
        });

        show.setOnClickListener(v -> {
            startActivity(new Intent(LoveActivity.this,UploadPhotoActivity.class));
        });

    }

}
